package com.venusj.singleton;

import java.io.Serializable;

/**
 * @author zhangjh
 * @date 2020/12/25
 * @desc 如何破坏单例模式
 */
public class MySingleton implements Serializable
{
    private MySingleton()
    {
        // 防止通过反射 导致破坏单例结构
        if(singleton != null)
        {
            throw new RuntimeException("instance constructor is called");
        }
    }

    private static volatile MySingleton singleton = new MySingleton();

    public static MySingleton getInstance()
    {
        if(singleton == null)
        {
            synchronized (MySingleton.class)
            {
                if(singleton == null)
                {
                    singleton = new MySingleton();
                }
            }
        }
        return singleton;
    }

    /**
     * 防止序列化 破坏单例结构
     * @return
     */
    private Object readResolve() {
        return getInstance();
    }
}
